<template>
	<view class="hotel-date-picker">
		<!-- 日历头部 -->
		<view class="calendar-header">
			<view class="month-selector">
				<view class="arrow-btn" @click="prevMonth">
					<text class="iconfont icon-left"> < </text>
				</view>
				<text class="current-month">{{ currentYear }}年{{ currentMonth + 1 }}月</text>
				<view class="arrow-btn" @click="nextMonth">
					<text class="iconfont icon-right"> > </text>
				</view>
			</view>
			<view class="week-days">
				<text v-for="(day, index) in weekDays" :key="index" class="week-day">{{ day }}</text>
			</view>
		</view>

		<!-- 日历主体 -->
		<view class="calendar-body">
			<view v-for="(day, index) in calendarDays" :key="index" class="day-cell" :class="{
          'empty': !day.date,
          'disabled': day.disabled,
          'full': day.full,
          'selected': isDateSelected(day.date),
          'check-in': isCheckInDate(day.date),
          'check-out': isCheckOutDate(day.date),
          'in-range': isInSelectedRange(day.date)
        }" @click="selectDate(day)">
				<view v-if="day.date" class="day-content">
					<text class="day-number">{{ formatDayNumber(day.date) }}</text>
					<!-- <text v-if="day.price" class="day-price" :class="{ 'special-price': day.isSpecial }">
						¥{{ day.price }}
					</text> -->
					<text v-if="day.full" class="day-status">已满</text>
				</view>
			</view>
		</view>

		<!-- 日历底部 -->
		<view class="calendar-footer">
			<view class="date-range-info">
				<view class="date-info">
					<text class="date-label">入住</text>
					<text class="date-value">{{ checkInDateFormatted || '请选择' }}</text>
				</view>
				<view class="stay-nights">
					<text>{{ stayNights }}晚</text>
				</view>
				<view class="date-info">
					<text class="date-label">离店</text>
					<text class="date-value">{{ checkOutDateFormatted || '请选择' }}</text>
				</view>
			</view>
			<button class="confirm-btn" :disabled="!canConfirm" @click="confirmSelection">确定</button>
		</view>

		<!-- 提示信息 -->
		<view v-if="type === 2" class="picker-tips">
			<text>特惠房型最多可预订3晚，且需提前一个月预订</text>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'HotelDatePicker',
		props: {
			// 选择器类型：1-普通，2-特惠房型（有限制）
			type: {
				type: Number,
				default: 1
			},
			// 初始入住日期
			initialCheckInDate: {
				type: String,
				default: ''
			},
			// 初始离店日期
			initialCheckOutDate: {
				type: String,
				default: ''
			},
			// 价格数据，格式：{ '2023-07-15': { price: 288, isSpecial: false } }
			priceData: {
				type: Object,
				default: () => ({})
			}
		},
		data() {
			const today = new Date();
			today.setHours(0, 0, 0, 0);

			return {
				weekDays: ['日', '一', '二', '三', '四', '五', '六'],
				today: today,
				currentYear: today.getFullYear(),
				currentMonth: today.getMonth(),
				checkInDate: this.initialCheckInDate || '',
				checkOutDate: this.initialCheckOutDate || '',
				selectionMode: 'checkIn', // 'checkIn' 或 'checkOut'
			};
		},
		computed: {
			// 一个月后的日期（用于特惠房型限制）
			oneMonthLater() {
				const date = new Date(this.today);
				date.setMonth(date.getMonth() + 1);
				return date;
			},

			// 格式化后的入住日期
			checkInDateFormatted() {
				return this.formatDate(this.checkInDate);
			},

			// 格式化后的离店日期
			checkOutDateFormatted() {
				return this.formatDate(this.checkOutDate);
			},

			// 入住天数
			stayNights() {
				if (!this.checkInDate || !this.checkOutDate) return 0;

				const start = new Date(this.checkInDate);
				const end = new Date(this.checkOutDate);
				return Math.round((end - start) / (1000 * 60 * 60 * 24));
			},

			// 是否可以确认选择
			canConfirm() {
				if (!this.checkInDate || !this.checkOutDate) return false;

				// 特惠房型限制最多入住3天
				if (this.type === 2 && this.stayNights > 3) return false;

				return true;
			},

			// 日历数据
			calendarDays() {
				const year = this.currentYear;
				const month = this.currentMonth;

				// 获取当月第一天是星期几
				const firstDay = new Date(year, month, 1).getDay();

				// 获取当月天数
				const daysInMonth = new Date(year, month + 3, 0).getDate();

				// 生成日历数组
				const days = [];

				// 填充月初空白
				for (let i = 0; i < firstDay; i++) {
					days.push({
						date: null
					});
				}

				// 填充日期
				for (let i = 1; i <= daysInMonth; i++) {
					const date = new Date(year, month, i);
					date.setHours(0, 0, 0, 0);
					const dateStr = this.formatDateString(date);
					
					
					// 判断是否禁用
					let disabled = false;
					let full = false;
					// if(this.type == 2 ){
					// 	disabled = true;
					// 	full = true;
					// }else{
					// 	disabled = false;
					// 	full = false;
					// }
					// 今天之前的日期禁用
					if (date < this.today) {
						disabled = true;
					}

					// 特惠房型的限制
					if (this.type === 2) {
						// 一个月内的日期标记为已满
						if (date < this.oneMonthLater) {
							full = true;
						}
					}

					// 获取价格数据
					let price = null;
					let isSpecial = false;

					if (this.priceData[dateStr]) {
						price = this.priceData[dateStr].price;
						isSpecial = this.priceData[dateStr].isSpecial || false;
					} else {
						// 如果没有价格数据，生成默认价格
						// 周末价格略高
						if (date.getDay() === 0 || date.getDay() === 6) {
							price = 288;
						} else {
							price = 245;
						}
					}

					days.push({
						date: dateStr,
						price,
						disabled,
						full,
						isSpecial
					});
				}

				// 计算需要填充的月末空白数量（确保总是显示6行）
				const totalCells = 42; // 6行7列
				const remainingCells = totalCells - days.length;

				// 填充月末空白
				for (let i = 0; i < remainingCells; i++) {
					days.push({
						date: null
					});
				}

				return days;
			}
		},
		mounted() {
			// 如果有初始日期，设置选择模式
			if (this.checkInDate && !this.checkOutDate) {
				this.selectionMode = 'checkOut';
			} else if (this.checkInDate && this.checkOutDate) {
				this.selectionMode = 'checkIn';
			}

			// 如果有初始日期，设置日历显示的月份
			if (this.checkInDate) {
				const date = new Date(this.checkInDate);
				this.currentYear = date.getFullYear();
				this.currentMonth = date.getMonth();
			}
		},
		methods: {
			// 格式化日期字符串 (YYYY-MM-DD)
			formatDateString(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			// 格式化日期显示
			formatDate(dateStr) {
				if (!dateStr) return '';

				const date = new Date(dateStr);
				const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				const weekday = weekdays[date.getDay()];
				return `${date.getMonth() + 1}月${date.getDate()}日 ${weekday}`;
			},

			// 格式化日期数字
			formatDayNumber(dateStr) {
				if (!dateStr) return '';

				const date = new Date(dateStr);
				return date.getDate();
			},

			// 判断日期是否被选中
			isDateSelected(dateStr) {
				if (!dateStr) return false;
				return dateStr === this.checkInDate || dateStr === this.checkOutDate;
			},

			// 判断是否是入住日期
			isCheckInDate(dateStr) {
				return dateStr === this.checkInDate;
			},

			// 判断是否是离店日期
			isCheckOutDate(dateStr) {
				return dateStr === this.checkOutDate;
			},

			// 判断日期是否在选择范围内
			isInSelectedRange(dateStr) {
				if (!dateStr || !this.checkInDate || !this.checkOutDate) return false;

				const date = new Date(dateStr);
				const start = new Date(this.checkInDate);
				const end = new Date(this.checkOutDate);

				return date > start && date < end;
			},

			// 选择日期
			selectDate(day) {
				if (!day.date || day.disabled || day.full) return;

				const selectedDate = day.date;

				if (this.selectionMode === 'checkIn') {
					// 选择入住日期
					this.checkInDate = selectedDate;
					this.checkOutDate = '';
					this.selectionMode = 'checkOut';
				} else {
					// 选择离店日期
					const inDate = new Date(this.checkInDate);
					const outDate = new Date(selectedDate);

					// 确保离店日期在入住日期之后
					if (outDate <= inDate) {
						uni.showToast({
							title: '离店日期必须在入住日期之后',
							icon: 'none'
						});
						return;
					}

					// 特惠房型限制最多入住3天
					if (this.type === 2) {
						const days = Math.round((outDate - inDate) / (1000 * 60 * 60 * 24));
						if (days > 3) {
							uni.showToast({
								title: '特惠房型最多可预订3晚',
								icon: 'none'
							});
							return;
						}
					}

					this.checkOutDate = selectedDate;
					this.selectionMode = 'checkIn';
				}
			},

			// 上个月
			prevMonth() {
				const today = new Date();
				if(today.getFullYear() == this.currentYear && this.currentMonth == today.getMonth()){
					return
				}
				if (this.currentMonth === 0) {
					this.currentYear--;
					this.currentMonth = 11;
				} else {
					this.currentMonth--;
				}
			},

			// 下个月
			nextMonth() {
				if (this.currentMonth === 11) {
					this.currentYear++;
					this.currentMonth = 0;
				} else {
					this.currentMonth++;
				}
			},

			// 确认选择
			confirmSelection() {
				if (!this.canConfirm) return;

				this.$emit('confirm', [this.checkInDate, this.checkOutDate]
				// {
				// 	checkInDate: this.checkInDate,
				// 	checkOutDate: this.checkOutDate,
				// 	nights: this.stayNights
				// }
				);
			}
		}
	}
</script>

<style lang="scss">
	.hotel-date-picker {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;

		.calendar-header {
			margin-bottom: 30rpx;

			.month-selector {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 20rpx;

				.current-month {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
				}

				.arrow-btn {
					width: 60rpx;
					height: 60rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					.iconfont {
						font-size: 28rpx;
						color: #666;
					}
				}
			}

			.week-days {
				display: flex;

				.week-day {
					flex: 1;
					text-align: center;
					font-size: 28rpx;
					color: #999;
					padding: 20rpx 0;
				}
			}
		}

		.calendar-body {
			display: flex;
			flex-wrap: wrap;

			.day-cell {
				width: 14.28%;
				height: 100rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				position: relative;

				&.empty {
					pointer-events: none;
				}

				&.disabled {
					pointer-events: none;
					opacity: 0.3;
				}

				&.full {
					.day-content {
						.day-status {
							font-size: 20rpx;
							color: #999;
						}
					}
				}

				&.selected {
					.day-content {
						background-color: #FF6000;

						.day-number {
							color: #fff;
						}

						.day-price {
							color: rgba(255, 255, 255, 0.8);
						}
					}
				}

				&.check-in {
					.day-content:after {
						content: '';
						position: absolute;
						right: 0;
						top: 0;
						bottom: 0;
						width: 10rpx;
						// background: linear-gradient(to right, #FF6000, rgba(255, 96, 0, 0.1));
					}
				}

				&.check-out {
					.day-content:before {
						content: '';
						position: absolute;
						left: 0;
						top: 0;
						bottom: 0;
						width: 10rpx;
						// background: linear-gradient(to left, #FF6000, rgba(255, 96, 0, 0.1));
					}
				}

				&.in-range {
					background-color: rgba(255, 96, 0, 0.1);
				}

				.day-content {
					width: 80rpx;
					height: 80rpx;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					border-radius: 50%;
					position: relative;

					.day-number {
						font-size: 28rpx;
						color: #333;
					}

					.day-price {
						font-size: 20rpx;
						color: #666;
						margin-top: 4rpx;

						&.special-price {
							color: #FF6000;
						}
					}

					.day-status {
						position: absolute;
						bottom: 0rpx;
						font-size: 20rpx;
						color: #999;
					}
				}
			}
		}

		.calendar-footer {
			margin-top: 40rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.date-range-info {
				display: flex;
				align-items: center;

				.date-info {
					display: flex;
					flex-direction: column;

					.date-label {
						font-size: 24rpx;
						color: #999;
					}

					.date-value {
						font-size: 28rpx;
						color: #333;
						margin-top: 8rpx;
					}
				}

				.stay-nights {
					margin: 0 20rpx;
					padding: 0 20rpx;
					height: 40rpx;
					display: flex;
					align-items: center;
					border-left: 1rpx solid #eee;
					border-right: 1rpx solid #eee;

					text {
						font-size: 24rpx;
						color: #666;
					}
				}
			}

			.confirm-btn {
				width: 160rpx;
				height: 70rpx;
				background-color: #FF6000;
				color: #fff;
				font-size: 28rpx;
				border-radius: 35rpx;
				display: flex;
				align-items: center;
				justify-content: center;

				&[disabled] {
					background-color: #ccc;
				}
			}
		}

		.picker-tips {
			margin-top: 20rpx;
			text-align: center;

			text {
				font-size: 24rpx;
				color: #FF6000;
			}
		}
	}
</style>